package com.beyondsoft.sabg.edu.business.advice;

import com.beyondsoft.sabg.edu.model.exception.GenericBusinessException;
import com.beyondsoft.sabg.edu.model.exception.InvalidParamException;
import com.beyondsoft.sabg.edu.model.exception.LoginException;
import com.beyondsoft.sabg.edu.model.vo.core.SimpleResponseVO;
import com.beyondsoft.sabg.edu.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 全局异常处理
 *
 * @Author Mo cr
 * @Date 2023/8/7
 */
@ControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler({LoginException.class})
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public SimpleResponseVO handleLoginError(GenericBusinessException ex) {
        logger.error(ex.getMessage(),ex);
        return ResponseUtil.failed(ex.getMessage());
    }

    @ExceptionHandler({GenericBusinessException.class, InvalidParamException.class})
    public ResponseEntity handleServiceError(GenericBusinessException ex) {
        return ResponseEntity.ok(ResponseUtil.failed(ex.getMessage()));
    }

    @ExceptionHandler({AccessDeniedException.class})
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public SimpleResponseVO handleAccessDeniedError(AccessDeniedException ex) {
        logger.error(ex.getMessage(),ex);
        return ResponseUtil.failed(ex.getMessage());
    }

    @ExceptionHandler({Exception.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public SimpleResponseVO handleUnExceptError(Exception ex) {
        logger.error(ex.getMessage(),ex);
        return ResponseUtil.failed(ex.getMessage());
    }

}
